<template>
  <div id="saveuser">
    <GoBack content="用户信息" backUrl="/userlist" />
    <div v-loading="loading" class="content">
      <el-form ref="formRef" :rules="formRule" :model="form" label-width="140px" class="form-input-m" :inline-message="true">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="form.username" type="text" placeholder="请输入用户名"></el-input>
        </el-form-item>
        <el-form-item prop="realname" label="真实姓名">
          <el-input v-model="form.realname" type="text" placeholder="请输入姓名"></el-input>
        </el-form-item>
        <el-form-item prop="jobNum" label="工号">
          <el-input v-model="form.jobNum" type="text" placeholder="请输入工号"></el-input>
        </el-form-item>
        <el-form-item prop="tel" label="联系电话">
          <el-input v-model="form.tel" type="text" placeholder="请输入电话"></el-input>
        </el-form-item>
        <el-form-item prop="status" label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="deptId" label="所属部门">
          <el-radio-group v-model="form.deptId">
            <el-radio v-for="dept in deptList" :label="dept.id" :key="dept.id">{{dept.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="roleId" label="用户角色">
          <el-radio-group v-model="form.roleId">
            <el-radio :label="role.id" v-for="role in roleList" :key="role.id">{{role.roleName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item element-loading-spinner="el-icon-loading">
          <el-button :loading="saving" type="primary" @click="saveUser(formRef)">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script setup lang="ts">
import GoBack from '../../components/GoBack.vue';
import { ref, reactive, getCurrentInstance } from 'vue';
import { notifyType, notifyMessage } from '../../utils/common';
import type { FormInstance } from 'element-plus';
import { AppStore } from '../../stores/store';
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let loading = ref(false);
let saving = ref(false);
let formRef = ref<FormInstance>();
let roleList: any = reactive([]);
let deptList: any = reactive([]);
let form: any = reactive({
  id: '',
  username: '',
  realname: '',
  tel: '',
  jobNum: '',
  status: 1,
  roleId: '',
  deptId: '',
  orgId: store.userInfo.orgId
});

let formRule = {
  username: [
    {
      required: true, //必填选项
      message: '请输入用户名',
      trigger: 'blur' //失去焦点时，出发提示
    },
    {
      min: 3,
      max: 20,
      message: '长度为3到20个字符',
      trigger: 'blur'
    }
  ],
  orgId: [
    {
      required: true,
      message: '请选择机构',
      trigger: 'change'
    }
  ],
  roleId: [
    {
      required: true,
      message: '请选择角色',
      trigger: 'change'
    }
  ]
};

init();
async function init() {
  loading.value = true;
  await findRoleList();
  await findDepartmentListByOrgId(form.orgId);

  if (proxy.$router.currentRoute.value.query.id) {
    form.id = proxy.$router.currentRoute.value.query.id;
    //获取角色列表
    const url = '/api/user/findUserSimple';
    proxy.$http
      .get(url, { params: { id: form.id, orgId: store.userInfo.orgId } })
      .then(async (res: any) => {
        if (res.status.code !== 1) {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        } else {
          form.username = res.data.user.username;
          form.realname = res.data.user.realname;
          form.jobNum = res.data.user.jobNum;
          form.tel = res.data.user.tel;
          form.status = res.data.user.status;
          form.orgId = res.data.user.orgId;
          if (res.data.user.roles.length > 0) {
            form.roleId = res.data.user.roles[0].roleId;
          }
          if (res.data.user.depts.length > 0) {
            form.deptId = res.data.user.depts[0].deptId;
          }
        }
        loading.value = false;
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
        loading.value = false;
      });
  } else {
    if (roleList[1] && roleList[1].id) {
      form.roleId = roleList[1].id;
    }
    loading.value = false;
  }
}

//根据社区服务中心获取部门列表
async function findDepartmentListByOrgId(orgId: string) {
  //根据省市区获取社区服务中心列表
  const url = '/api/sys/findDepartmentListByOrgId';
  const res = await proxy.$http.get(url, { params: { orgId } });
  deptList.push(...res.data.deptList);
}

//获取角色列表
async function findRoleList() {
  const url = '/api/sys/findRoleList';
  const res: any = await proxy.$http.get(url);
  if (res && res.status.code === 1) {
    roleList.push(...res.data.roleList);
  }
}

//保存
function saveUser(formEl: any) {
  if (!formEl) return;
  formEl.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    saving.value = true;
    const postData = {
      id: form.id,
      username: form.username,
      realname: form.realname,
      tel: form.tel,
      jobNum: form.jobNum,
      status: form.status,
      deptId: form.deptId,
      roleId: form.roleId,
      orgId: form.orgId
    };

    let url = '';
    if (form.id) {
      url = '/api/user/editUser';
    } else {
      url = '/api/user/addUser';
    }
    proxy.$http
      .post(url, postData)
      .then((res: any) => {
        if (res.status.code === 1) {
          notifyMessage('保存成功', notifyType.success, proxy);
          form.id = res.data.sysUserId;
        } else {
          notifyMessage(res.status.msg, notifyType.warning, proxy);
        }
        saving.value = false;
      })
      .catch((err: string) => {
        notifyMessage(err, notifyType.warning, proxy);
        saving.value = false;
      });
    return true;
  });
}
</script>
<style lang="scss" scoped>
#saveuser {
  .sys-tab-form {
    .el-form-item--default {
      margin-bottom: 10px !important;
    }
  }
  :deep(.el-tabs__item) {
    line-height: 30px !important;
  }
}
</style>